from flask import Blueprint, request, jsonify
from flask_bcrypt import Bcrypt
from models.models import User, db
from sqlite import sellBill, get_Bill
from usilt.statusCode import statusCodes

# 创建 Blueprint
api_bp = Blueprint('api', __name__, url_prefix='/api')

# 初始化 Bcrypt
bcrypt = Bcrypt()


# 统一错误响应
def error_response(message, status_code):
    return jsonify({'message': message}), status_code


# 成功响应
def success_response(message, data=None, status_code=200):
    response = {'message': message}
    if data is not None:
        response['data'] = data
    return jsonify(response), status_code


# 用户注册
@api_bp.route('/user/registerUser', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    if not username or not password:
        return error_response('Username and password are required', 400)
    hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
    user = User(username=username, password=hashed_password)
    db.session.add(user)
    db.session.commit()
    return success_response('User registered successfully', status_code=201)


# 用户登录
@api_bp.route('/user/userLogin', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    if not username or not password:
        return error_response('Username and password are required', 400)
    user = User.query.filter_by(username=username).first()
    if user and bcrypt.check_password_hash(user.password, password):
        return success_response('Login successful')
    return error_response('Invalid username or password', 401)


# 接收数据
@api_bp.route('/user/receive_data', methods=['POST'])
def receive_data():
    data = request.get_json()
    if not data:
        return error_response('未接收到有效数据', 400)
    try:
        sellBill(data)
        return success_response('数据接收成功')
    except Exception as e:
        print(f"Error: {e}")
        return error_response('数据处理失败', 500)


# 获取数据
@api_bp.route('/user/get_data', methods=['GET'])
def get_data():
    bills = get_Bill(data=None)
    return jsonify({"code": statusCodes["成功"], "data": bills, "message": "ok"})
